package com.lmt.filter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.reactive.result.view.RequestContext;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;

@Component
@Slf4j
public class TimeGlobleFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 从请求头中获取token
        List<String> token = exchange.getRequest().getHeaders().get("token");
        // 打印日志
        log.info("check token = {}", token);
        // 检查token是否正确合规
        if (token == null || token.isEmpty()) {
            // 设置响应对象
            ServerHttpResponse response = exchange.getResponse();
            // 构建错误信息
            HashMap<Object, Object> hashMap = new HashMap<>();
            hashMap.put("success", false);
            hashMap.put("message", "未登录");
            DataBuffer dataBuffer = null;
            // 把HashMap转为JSON字符串
            try {
                byte[] bytes = JSON.toJSONString(hashMap).getBytes("utf-8");
                // 把结果放到响应里去************
                dataBuffer = response.bufferFactory().wrap(bytes);
                // 设置完成,直接响应
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                response.getHeaders().add("Content-Type","application/json;charset=UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            // 把结果响应给客户端************
            return response.writeWith(Mono.just(dataBuffer));

        }
        log.info("token not is null can go");
        // 固定写法**********
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}